package com.huawei.codearts.tools.aop;

import com.huawei.codearts.service.WbIpService;
import com.huawei.codearts.tools.utils.JsonUtils;
import com.huawei.codearts.tools.utils.ResultUtils;
import com.huawei.codearts.tools.utils.WebUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;

/********************************************************************************
 ** @date ：2024/08/13
 ** @description ：自定义拦截器 拦截ip
 *********************************************************************************/
@Slf4j
public class WBListIntercept implements HandlerInterceptor {

    @Autowired
    private WbIpService wbIpService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddress = WebUtil.getIP();
        log.info("机主的ip是:"+ipAddress);
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        if(cxt != null && cxt.getBean(WbIpService.class) != null && wbIpService == null) {
            wbIpService =cxt.getBean(WbIpService.class);
        }
        if (wbIpService.getIp(ipAddress)) {
            return true;
        } else {
            returnJson(response, JsonUtils.objectToJson(ResultUtils.error(1002, "访问权限受限制")));
            return false;
        }
    }

    /********************************************************************************
     ** @date ：2024/08/13
     ** @description ：设置请求拦截返回参数
     *********************************************************************************/
    private void returnJson(HttpServletResponse response, String result) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
